package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.config.login.Userparam;
import com.example.demo.datasource.multi.entity.mytasklistentity;
import com.example.demo.datasource.multi.entity.Workflowentity;
import com.example.demo.entity.tasklist.tasklistbase;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
public class tasklistcontroller {

@Autowired
com.example.demo.datasource.multi.entity.mytasklistentity mytasklistentity;
@Autowired
com.example.demo.datasource.multi.dao.tasklistmapper tasklistmapper;

    @Value("${user.home}")
    private String userName;

    @Autowired
    com.example.demo.util.getip getip;
    /**
     * 端口
     */
    @Value("${server.port}")
    private String port;

    @Autowired
    com.example.demo.entity.tasklist.tasklistbase tasklistbase;
    @Autowired
    com.example.demo.datasource.multi.dao.usermapper usermapper;

    @ResponseBody
    @RequestMapping("/gettasklistbyuser")
    public JSONObject gettasklistbyuser(HttpServletRequest request){

        HttpSession session1 = request.getSession();
        //统一拦截（查询当前session是否存在user）(这里user会在每次登录成功后，写入session)
        Userparam user = (Userparam) session1.getAttribute(session1.getId());
        log.info("获取用户信息:"+user.getUsername());

        String sqlx="select * from user where username = '"+user.getUsername()+"'";

        com.example.demo.datasource.multi.entity.user theuser=usermapper.getuser(sqlx);

        String sql=null;

        if (theuser.getRolevalue().equals("Super")){

            sql="SELECT DISTINCT a.id,a.approvalstatus,a.applicationawards,a.createtime,a.type,a.pkid,b.avatar,b.realname,a.workflownumber, " +
                    "e.name AS college,f.name AS profession,g.name AS tclass " +
                    "FROM application a " +
                    "LEFT JOIN userinfo b ON a.userid = b.userid  " +
                    "left JOIN workflow c ON c.pkid = a.pkid " +
                    "LEFT JOIN user d on d.id = b.userid " +
                    "LEFT JOIN organization e on e.code = d.college " +
                    "LEFT JOIN organization f on f.code = d.profession " +
                    "LEFT JOIN organization g on g.code = d.tclass " +
                    "WHERE " +
                    "a.approvalstatus = '4' " +
                    "OR (a.approvalstatus = '5' AND c.`handler` = '"+user.getUsername()+"')";
            System.out.println("sql:"+sql);

        }else if (theuser.getRolevalue().equals("Department")){
            sql="SELECT DISTINCT a.id,a.approvalstatus,a.applicationawards,a.createtime,a.type,a.pkid,b.avatar,b.realname,a.workflownumber, " +
                    "e.name AS college,f.name AS profession,g.name AS tclass " +
                    "FROM application a " +
                    "LEFT JOIN userinfo b ON a.userid = b.userid  " +
                    "left JOIN workflow c ON c.pkid = a.pkid " +
                    "LEFT JOIN user d on d.id = b.userid " +
                    "LEFT JOIN organization e on e.code = d.college " +
                    "LEFT JOIN organization f on f.code = d.profession " +
                    "LEFT JOIN organization g on g.code = d.tclass " +
                    "WHERE " +
                    " (a.approvalstatus = '2' and d.college = '"+theuser.getCollege()+"') " +
                    "OR (a.approvalstatus = '3' AND c.`handler` = '"+user.getUsername()+"')";
            System.out.println("sql:"+sql);

        }else {
            sql="select a.id,a.approvalstatus,a.applicationawards,a.createtime,a.type,a.pkid,b.avatar,b.realname,a.workflownumber, " +
                    "e.name AS college,f.name AS profession,g.name AS tclass " +
                    "from application a " +
                    "left join userinfo b ON a.userid = b.userid " +
                    "LEFT JOIN user d on d.id = b.userid " +
                    "LEFT JOIN organization e on e.code = d.college " +
                    "LEFT JOIN organization f on f.code = d.profession " +
                    "LEFT JOIN organization g on g.code = d.tclass " +
                    "WHERE " +
                    "b.realname = '"+user.getUsername()+"'";
            System.out.println("sql:"+sql);
        }


        List<mytasklistentity> thetasklist= tasklistmapper.gettasklistbyuser(sql);
        System.out.println(thetasklist);



        InetAddress ia = null;
        try {
            ia = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String ip = getip.getip(request);

        List<tasklistbase> tlb = new ArrayList<>();//整个列表

        for (mytasklistentity mm: thetasklist
             ) {
            String newfilename = "http://" + ip + ":" + port + "/files/"+mm.getAvatar();
            mm.setAvatar(newfilename);
            if (mm.getType().equals("individual")){
                mm.setType("个人");
            }else {
                mm.setType("组织");
            }

            tasklistbase ll = new tasklistbase();  //列表的每一行
            ll.setId(mm.getId());
            ll.setTitle(mm.getTclass()+" "+mm.getRealname()+"申请"+mm.getApplicationawards()+"（"+mm.getType()+"）");
            ll.setCreatetime(mm.getCreatetime());
            ll.setCreater(mm.getRealname());
            ll.setExtra("详情");
            ll.setAvatar(mm.getAvatar());
            ll.setType(mm.getType());
            ll.setDaiban(thetasklist.size()); //待办
            ll.setPkid(mm.getPkid());


           /* Workflowentity wf1= new Workflowentity();
            wf1.setId(1);
            wf1.setStatus("编辑中");
            wf1.setHandletime("2021-10-13 21:32");
            wf1.setHandler("张三");
            wf1.setNumber(1);
            wf1.setHandleaction("编辑");

            Workflowentity wf2= new Workflowentity();
            wf2.setId(2);
            wf2.setStatus("已提交");
            wf2.setHandletime("2021-11-22 22:32");
            wf2.setHandler("张三");
            wf2.setNumber(2);
            wf2.setHandleaction("提交");

            Workflowentity wf3= new Workflowentity();
            wf3.setId(3);
            wf3.setStatus("学院审批中");
            wf3.setHandletime("2021-12-12 12:32");
            wf3.setHandler("资助办小马");
            wf3.setNumber(3);
            wf3.setHandleaction("批准");*/


            String sql1="select a.id,a.status,a.handletime,a.handler,a.handleaction,b.dictname from workflow a left join dict b on a.status = b.code WHERE pkid = '"+mm.getPkid()+"' ORDER BY a.number";
            System.out.println(sql1);

            List<Workflowentity> lwf= tasklistmapper.getWorkflowlistbypkid(sql1);
            System.out.println(lwf);
            for (Workflowentity wff:lwf
                 ) {
                String dictname = wff.getDictname();
                wff.setStatus(dictname);
            }

            /*List<Workflowentity> lwf = new ArrayList<>();
            lwf.add(wf1);
            lwf.add(wf2);
            lwf.add(wf3);
            System.out.println(lwf);*/

            int sizei=Integer.parseInt(mm.getApprovalstatus());

            List<String> lss=new ArrayList<>();
            lss.add("编辑");
            lss.add("提交");
            lss.add("初审审批中");
            lss.add("初审通过");
            lss.add("终审审批中");
            lss.add("终审通过");

//            if (mm.getApprovalstatus().equals("0")){
//                ll.setCurrent("1");//步骤条节点
//            }else
                if (mm.getApprovalstatus().equals("7")||mm.getApprovalstatus().equals("6")){
                ll.setCurrent(mm.getWorkflownumber());//步骤条节点
                ll.setPercent(100);
            }else {
                ll.setCurrent(mm.getWorkflownumber());//步骤条节点

                ll.setPercent(sizei*(100/6));

                while (sizei<6){

                    Workflowentity wf10= new Workflowentity();
                    wf10.setId(sizei);
                    wf10.setStatus(lss.get(sizei));
                    sizei++;
                    lwf.add(wf10);

                }

            }



            ll.setWorkflowlist(lwf);
            tlb.add(ll);

        }

        Map<String, Object> result5 = new HashMap<String,Object>();
        result5.put("code",0);
        result5.put("result",tlb);
        result5.put("message","获取成功!");
        result5.put("type","success");
        System.out.println("获取成功！");

        JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
        System.out.println(result8);

        return result8;

    }


}
